#Copyright Okhtay Shoghi 2008

require 'uranium/constants'
require 'uranium/utils'

class Log
    DATABASE    = 0
    DEBUG       = 1
    WARN        = 2
    DEFAULT     = 3
    ERROR       = 3
    NONE        = 4

    @@logs      = Hash.new
    @@log_level = DEBUG
    
    def self.init_log(name)
        @@logs[name] = File.open("#{LOG_DIRECTORY}/logs/#{name}_#{Time.new.strftime('%y%m%d_%H%M%S')}.log", "w+")
    end
    
    def self.write_log(str, log_name='default', level='',time=true)
        if (LOG_TO_FILE)
            self::init_log(log_name) if not @@logs.has_key?(log_name)
            
            t_str = time ? "#{Time.new.strftime('%H:%M:%S')}: " : ''
            @@logs[log_name].write("#{level}#{t_str}#{str}\n")        
        end
    end
    
    def self.set_log_level(level)
        @@log_level = level
    end

    def self.line
        puts "\n"    
    end
    
    def self.get_log_level
        return @@log_level
    end
    
    def self.rc_debug(str, log_name='rclistener')
        write_log(str, log_name, 'LISTENER ')
    end
  
    def self.dbdebug(str, log_name='mysql')
        return unless @@log_level <= DATABASE
    
        puts "DATABASE: #{str}"
        write_log(str, log_name, 'DATABASE ')
    end
    
    def self.debug(str, log_name='default')
        return unless @@log_level <= DEBUG
    
        puts "DEBUG: #{str}"
        write_log(str, log_name, 'DEBUG ')
    end

    def self.test(name)
		if is_windows?
			x = 10
		else
	    	cols = `tput cols`.to_i
			x = (cols - 2 - name.length) / 2
		end

        str = "#{'='*x} #{name} #{'='*x}"
        puts str
        write_log(str,'default','',false)
    end
    
    def self.error(e, log_name='default')
        puts "ERROR: #{e.to_s}"
        write_log(e.to_s, log_name, 'ERROR ')
    end
    
    def self.warn(str)
        puts str
    end
end
